import { _decorator, Component, Node, Vec2, UITransform, EventTouch, Vec3, view } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 摇杆控制器
 * 
 * 功能：
 * 1. 处理触摸输入
 * 2. 计算移动方向和强度
 * 3. 提供摇杆状态信息
 * 4. 支持多点触控
 * 
 * 特点：
 * 1. 可配置的摇杆参数
 * 2. 支持固定/跟随模式
 * 3. 平滑的输入处理
 * 4. 多设备适配
 */
@ccclass('JoystickController')
export class JoystickController extends Component {
    @property(Node)
    private joystickBg: Node | null = null;

    @property(Node)
    private joystickHandle: Node | null = null;

    private static _instance: JoystickController | null = null;
    private moveDirection: Vec2 = new Vec2();
    private isMoving: boolean = false;
    private joystickRadius: number = 0;
    private initialPos: Vec2 = new Vec2();
    private touchId: number = -1;

    public static get instance(): JoystickController {
        if (this._instance === null) {
            throw new Error('JoystickController instance is not created yet!');
        }
        return this._instance;
    }

    onLoad() {
        if (JoystickController._instance === null) {
            JoystickController._instance = this;
            this.initJoystick();
        } else {
            this.node.destroy();
        }
    }

    private initJoystick() {
        if (!this.joystickBg || !this.joystickHandle) return;

        // 获取摇杆背景的半径
        const bgTransform = this.joystickBg.getComponent(UITransform);
        this.joystickRadius = bgTransform!.contentSize.width / 2;
        
        // 记录初始位置
        this.initialPos = new Vec2(this.joystickBg.position.x, this.joystickBg.position.y);

        // 注册触摸事件
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    private onTouchStart(event: EventTouch) {
        // 只在屏幕左半边响应
        const touchPos = event.getLocation();
        const viewSize = view.getVisibleSize();
        if (touchPos.x > viewSize.width / 2) return;

        this.touchId = event.getID();
        const pos = event.getUILocation();
        this.joystickBg!.setPosition(new Vec3(pos.x, pos.y, 0));
        this.updateJoystickPosition(pos);
    }

    private onTouchMove(event: EventTouch) {
        if (event.getID() !== this.touchId) return;

        const pos = event.getUILocation();
        this.updateJoystickPosition(pos);
    }

    private onTouchEnd(event: EventTouch) {
        if (event.getID() !== this.touchId) return;

        this.touchId = -1;
        this.isMoving = false;
        this.moveDirection = Vec2.ZERO;
        this.joystickBg!.setPosition(new Vec3(this.initialPos.x, this.initialPos.y, 0));
        this.joystickHandle!.setPosition(Vec3.ZERO);
    }

    private updateJoystickPosition(touchPos: Vec2) {
        const bgPos = this.joystickBg!.position;
        const direction = new Vec2(
            touchPos.x - bgPos.x,
            touchPos.y - bgPos.y
        );

        // 计算摇杆方向和距离
        const distance = direction.length();
        
        if (distance > this.joystickRadius) {
            direction.multiplyScalar(this.joystickRadius / distance);
        }

        // 更新摇杆手柄位置
        this.joystickHandle!.setPosition(new Vec3(direction.x, direction.y, 0));

        // 更新移动方向（归一化）
        this.moveDirection = direction.normalize();
        this.isMoving = distance > 0;
    }

    public getMoveDirection(): Vec2 {
        return this.moveDirection;
    }

    public getIsMoving(): boolean {
        return this.isMoving;
    }

    onDestroy() {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
} 